How to create buffers around shapefile features in Python


GIS in Python: Buffering

Buffering allows you to identify or define an area within a specified distance around a feature for spatial analysis or to indicate proximity or accessibility conditions. Buffering can be done on all three types of features: point, line, area. For example, you realize there is a correlation between long ambulance evacuation times and patient death rates. During the COVID-19 pandemic, patients with respiratory emergencies are particularly vulnerable to long evacuations. Thus, you would like to study how many African Americans in New York state live within a 5-mile radius of a hospital and create a map that assists both first responders and African Americans living in New York state in finding the nearest hospital with a 5-mile radius of a medical emergency location. You now have two shapefiles at hand, one is a New York state census tract shapefile with an attribute of African Americans population and the other is a shapefile of locations of all the hospitals in New York state. Let’s conduct this analysis using Python and the GeoPandas package. You can use the read_file() method from the geopandas package to read shapefiles and then convert the coordinate reference systems of the shapefiles to an appropriate one for the geography of your data in unit of metre by using the to_crs() method, and then create polygon buffers around features of interest using the buffer() method. Here is the data for this exercise.


Part A: Install and Launch Jupyter Notebook via Anaconda

If you already have Anaconda downloaded and installed, you can skip Part A and directly start the analysis in Part B. Make sure you also have packages pandas, geopandas of version 0.7 or higher, matplotlib, and descartes installed in the environment where you would like to conduct this analysis. Note starting with the version 0.7, geopandas made a big change in Coordinate Reference System representation and hence some code syntax differs before and after version 0.7, as described here and here. As our tutorial writes in new version syntax, please make sure your geopandas is of version 0.7 or later in order to run the code with no error. You may check the version of geopandas and upgrade it within your environment either in Anaconda Navigator or in your terminal window.

1) First, download Anaconda. Anaconda is a free and open-source distribution of Python. You can use Anaconda to install IDEs (integrated development environments where you can write and run code) and packages like Pandas and Geopandas. Go to the link to download Anaconda, https://www.anaconda.com/products/individual, and then open the .exe file that was downloaded and follow the instructions in the installation wizard prompt.


2) Once installation is complete, open Anaconda Navigator and create a new environment for your project. A Conda environment is a directory that contains a specific collection of Conda packages that you have installed. Conda has a default environment called 'base' that includes a Python installation and some core system libraries and dependencies of Conda. It is a “best practice” to avoid installing additional packages into your base environment, and, instead, create an isolated environment to manage packages and dependencies in a new project.

Click on the Environments selection in the left sidebar menu and then click on the 'Create' at the bottom. This will open a dialog box prompting you to create a name for the new environment. You can give any name for your new environment. Here, we use 'GIS_in_Python' as the environment name. Then click the 'Create' button within the dialog box to finish the creation.


3) Once you have your project environment set up, click on the arrow to the right of your new environment, 'GIS_in_Python' in this example, and select Open Terminal. This will give you access to the command line interface on your computer in a window.


4) Install the packages/libraries necessary for the analysis by entering the following commands in the opened terminal, one line at a time:
conda install pandas
conda install geopandas
conda install matplotlib
conda install descartes


5) Once you have those libraries all installed, select the new environment, 'GIS_in_Python' in this example, in the 'Applications on' dropdown menu, and then click "install" and "launch" under Jupyter Notebook. Jupyter Notebook will open in your web browser (it does not require the internet to work).


6) In Jupyter Notebook, navigate to the folder where you saved the code file you plan to use and open the .ipynb file (the extension for Jupyter Notebook files written in Python) to run it in the Notebook. If you would like to create a new .ipynb file, browse to the folder in which you would like to save your Notebook, then click the "New" dropdown button on the top-right and select "Python 3". Your new Notebook will open in a new tab in your browser. If you want to create a new directory using the Jupyter Notebook dashboard, click the "New" dropdown button and then select "Folder". To add files from your local machine, click the "Upload" button on the top-right to open a file chooser window and then choose the file you wish to upload.


Part B: Read Data File and Perform Buffering

1) Import necessary packages/libraries.


2) Use the gpd.read_file() function from the geopandas package to read the shapefile. Optionally, you can use the head() method to return the first 5 rows of the GeoDataFrame, and use the .shape attribute to check the number of rows and columns of the GeoDataFrame in the returned tuple (number of rows, number of columns). For this example, the number of rows of the 'NYS_hospitals' and the 'NYS_population' suggest that there are 234 hospitals and 4918 census tracts in New York state.

Let’s look at the shape of the shapefiles for 'NYS_hospitals' and 'NYS_populuations'.

You may also use matplotlib for plotting to generate an overview of your GeoDataFrame.


3) Before buffering, use the .crs attribute to check the current Coordinate Reference System (CRS)/projection of your spatial data, and if they are not projected into a projection using unit of metre, use the to_crs() method to re-project the data to a projection appropriate for the geographical area of your data and based in metre. This step ensures that you will be able to create buffers in distance unit. Also, make sure that all layers involved in the analysis have the same projection as it makes it possible to analyze the spatial relationships between layers.

In this example, 'NYS_hospitals' and 'NYS_population' are the two GeoDataFrame that we need to examine their projection (.crs). Both 'NYS_hospitals' and 'NYS_population' are in EPSG:4269 of which CRS is in latitude and longitude in decimal degrees, so we need to re-project the two layers. A bit of research suggests that EPSG:3627 would be an appropriate projection for New York state in the unit of metre. Therefore, we convert the CRS of 'NYS_hospitals' and 'NYS_population' to EPSG:3627 (.to_crs('epsg:3627')) so that next we can create buffers in metres.


4) Use the buffer() method to perform buffering. The buffer() method takes in a buffer distance and returns a GeoSeries of geometries with boundaries the buffer distance away from the input geometries. For this example, the geometries are points in the 'NYS_hospitals' (NYS_hospitals['geometry']) which are the locations of hospitals, and we create a 8km (around 5 miles) radius buffer around the hospital points (.buffer(8000)). Optionally, you can use the head() method to return the first 5 elements of the GeoSeries.


5) You can now use matplotlib to generate an overview of the buffers. For this example, based on the map of 'NYS_population' we generated in the Step 2, further specify that:


6) Now with the buffers generated, we can study the question of how many African American in New York state live within 5 miles to hospitals through the following steps.

Optionally, we can use len() function to check the length of the list 'idx_tracts_close2hospital' and it shows that the number of census tracts that are close to at least one hospital within 5 miles is 4400.

To have a look at the buffers around hospitals and the tracts that have at least one intersection with the buffers, we can again use matplotlib to do the visualization. Based on the map we generated in the Step 5, we add on top of it the following specifications.

Now let’s calculate how many African Americans in New York state live within 5 miles to hospitals. Remember the variable 'idx_tracts_close2market' saves the indexes of tracts that intersect with at least one buffer of hospitals. We use the indexes to get the population of African Americans who live in each of these tracts (NYS_population.iloc[idx_tracts_close2hospital, : ]['Blk/AfA']), then use astype() method to convert the data type to be integer and then use sum() method to calculate the sum of the populations. The value is saved in a new variable, 'blacks_within_5miles', which is then divided by the total number of African Americans in all 4918 tracts.

In conclusion, the calculation result shows that 97.96% African Americans in New York state live within 5 miles distance to at least one hospital.